from aiocqhttp import CQHttp
from requests_html import HTMLSession
from threading import Thread
import json
import time

import timer


bot = CQHttp(access_token='your-gdfhuighuidfg', enable_http_post=False)
session = HTMLSession()
latest_pub_date = 0

cache_life = 60  # cache有效时长（s）
_cache = {
    "cache_time": 0,
    "data": None
}


def get_count(r):
    dataA = r.html.find('#getStatisticsService', first=True).text
    dataA = dataA[36:-11]
    dataA = json.loads(dataA)
    return dataA


def get_messages(r):
    """最新疫情情况"""
    dataB = r.html.find('#getTimelineService', first=True).text
    dataB = dataB[34:-11]
    dataB = json.loads(dataB)
    return dataB


def get_zone(r):
    """省市疫情信息"""
    data = r.html.find("#getAreaStat", first=True).text
    data = data[27:-11]
    data = json.loads(data)
    return data


def get_rumor(r):
    """辟谣与防护"""
    data = r.html.find("#getIndexRumorList", first=True).text
    data = data[33:-11]
    data = json.loads(data)
    return data


async def get_session(event):
    # update cache
    if time.time() - _cache["cache_time"] >= cache_life:
        await bot.send(event, "缓存过期，正在获取数据")     # is 
        _cache["data"] = session.get('https://3g.dxy.cn/newh5/view/pneumonia')    # 如果报错则不是可等待对象，删除await
        _cache["cache_time"] = time.time()
    else:
        await bot.send(event, "正在使用缓存")

    return _cache["data"]


@bot.on_message("group")
async def handle_msg(event):
    if event["message"] == "机器人信息":
        message = "本机器人使用python编程语言开发，采用酷q相关库开发的机器人,\
项目地址:Github:https://github.com/mzdluo123/wuhan_bot\n \
由luo123开发\n\tluo123(项目主要负责人):\n\t\tqq: 2314572588\n\t\tGithub: https://github.com/mzdluo123\n\t \
Sugobet(本项目第一贡献者, 对本项目进行优化与更新): \n\t\tqq: 321355478\n\t\tGithub: https://github.com/Sugobet "
        await bot.send(event, message)
        return

    if event['message'] == '疫情统计':
        r = await get_session(event)
        data = get_count(r)
        message = f'确诊:{data["confirmedCount"]} 疑似:{data["suspectedCount"]} 治愈:{data["curedCount"]} 死亡:{data["deadCount"]}'
        await bot.send(event, message)
        dataB = get_messages(r)
        latest = dataB[0]
        message = f"{latest['title']}\n{latest['summary']}\n{latest['sourceUrl']}"
        await bot.send(event, message)
        return

    if event['message'] == '信息':
        message = '''以下是疫情信息链接
https://news.ifeng.com/c/special/7tPlDSzDgVk
https://3g.dxy.cn/newh5/view/pneumonia
https://news.163.com/special/epidemic/?spssid=7283291fcdba1d8c2d13ee3da2cfb760&spsw=7&spss=other
https://m.sohu.com/cbd/sp/NCOV2019
http://m.app.caixin.com/m_topic_detail/1473.html'''
        await bot.send(event, message)
        return

    if event['message'] == '地区':
        r = await get_session(event)
        message = ""
        data = get_zone(r)
        for i in data:
            message += f'{i["provinceShortName"]} '
        message += f'\n发送 查询 <省份> or 查询 <城市> 来查询对应人数'
        await bot.send(event, message)
        return

    if event['message'][:3] == '查询 ':
        r = await get_session(event)
        data = get_zone(r)
        for i in data:
            inf = event["message"][3:]
            if inf == i["provinceShortName"] or inf == i["provinceName"]:
                message = f'{i["provinceShortName"]}: \n\t确诊:{i["confirmedCount"]} \n\t治愈:{i["curedCount"]} \n\t死亡:{i["deadCount"]}'
                await bot.send(event, message)
                return
            else:
                for a in i['cities']:                
                    if inf == a["cityName"]:
                        message = f'{i["provinceShortName"]}-{a["cityName"]} 确诊:{a["confirmedCount"]} 治愈:{a["curedCount"]} 死亡:{a["deadCount"]}\n'
                        await bot.send(event, message)
                        return

        await bot.send(event, '暂无数据')
        return

    if event['message'] == '辟谣':
        r = await get_session(event)
        data = get_rumor(r)
        message = ''
        for i in data:
            message += f'{i["title"]}\n{i["mainSummary"]}\n{i["body"]}\n'
        message += "更多信息请到丁香园网站查询"
        await bot.send(event,message)


if __name__ == "__main__":
    s1 = Thread(target=timer.schedar_run)
    s1.start()
    bot.run(host='127.0.0.1', port=6700)
